package shiro;

import bean.User;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import service.inter.LoginService;

public class CustomRealm extends AuthorizingRealm {
    @Autowired
    private LoginService loginService;

    /**
     * 权限配置
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 1.获取登录用户名
        String name = (String) principalCollection.getPrimaryPrincipal();
        // 2.查询用户名
        User user = loginService.getUserByName(name);
        // 3.添加角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        user.getRoles().stream().forEach(role -> {
            simpleAuthorizationInfo.addRole(role.getRoleName());
            role.getPermissions().stream().forEach(permissions -> {
                simpleAuthorizationInfo.addStringPermission(permissions.getPermissionsName());
            });
        });
        return simpleAuthorizationInfo;
    }

    /**
     * 认证配置
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        if (StringUtils.isEmpty(authenticationToken.getPrincipal())) {
            return null;
        }
        String name = authenticationToken.getPrincipal().toString();
        User user = loginService.getUserByName(name);
        if(user==null){
            return null;
        }else{
            return new SimpleAuthenticationInfo(name, user.getPassword(), getName());
        }
    }
}
